<template>
  <el-dialog
    title="注意：<br>便签表示换行"
    v-model="state.visible"
    width="900px"
    >
    <div class="add">
      <el-card class="add-container">
        <span><b>录入题目</b></span>
        <el-form :model="state.questionForm" :rules="state.rules" ref="questionRef" label-width="100px" class="questionForm">
          <el-form-item label="题目：" prop="content">             
          <!-- 这里放富文本框 -->
          <div style="width:700px">
            <editor v-model="state.questionForm.content" @input="(val)=> {state.questionForm.content=val}"></editor>
          </div>
          </el-form-item>
          <el-form-item label="题目插图：" prop="pictures" >
            <el-input  v-model="state.questionForm.pictures" type="textarea" disabled></el-input>
          </el-form-item>
          <!-- 上传题目图片 -->
          <div>
            <el-upload              
              :action="state.uploadImgServer"
              list-type="picture-card"
              ref="uploadPictureRef"
              name="images"
              :headers="{
                token: state.token
              }"
              accept=".jpg,.jpeg,.png"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="upLoadSuccess"
              :auto-upload="true"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
           </div>
        
       
            <el-form-item label="知识点：" prop="knowledgepoint">
              <el-select v-model="state.questionForm.knowledgepoint" :disabled="knowledgepointId>=0" size="small" class="m-2">
                <el-option
                  v-for="item in knowledgepointOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

          <el-form-item label="答案：" prop="answer">
            <el-input style="width: 300px" v-model="state.questionForm.answer" placeholder="请输入参考答案" clearable></el-input>
          </el-form-item>
          <el-form-item label="解析：" prop="explain">
            <el-input v-model="state.questionForm.explain" placeholder="输入解析" clearable></el-input>
          </el-form-item>

          <el-form-item label="解析插图：" prop="pictures_explain" >
            <el-input  v-model="state.questionForm.pictures_explain" type="textarea" disabled></el-input>
          </el-form-item>
          <!-- 上传解析图片 -->
          <div>
            <el-upload              
              :action="state.uploadImgServer"
              list-type="picture-card"
              ref="uploadPictureExplainRef"
              name="images"
              :headers="{
                token: state.token
              }"
              accept=".jpg"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleExplainRemove"
              :on-success="upLoadExplainSuccess"
              :auto-upload="true"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
           </div>

          <el-form-item label="来自：" prop="reference">
            <el-input style="width: 300px" v-model="state.questionForm.reference" placeholder="来自什么资料"></el-input>
          </el-form-item>
          
          <el-form-item label="题型：" prop="type">
            <el-select v-model="state.questionForm.type" class="m-2" placeholder="题型" size="small">
              <el-option
                v-for="item in questionTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>            
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty_level">            
            <el-select v-model="state.questionForm.difficulty_level" class="m-2" placeholder="难度：" size="small">
              <el-option
                v-for="item in difficultyLevelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="公开：" prop="open_level">
            <el-select v-model="state.questionForm.open_level" class="m-2" placeholder="公开/私密" size="small">
              <el-option
                v-for="item in openLevelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>           
          </el-form-item> 
        </el-form>
            <el-button type="primary" @click="submitAddOneQuestion">提交</el-button>
            <el-button type="warning" @click="close()">取消</el-button>
        
      </el-card>
      
    </div>
  </el-dialog>
</template>


<script setup>
import Editor from '@/components/TinymceEditor.vue';
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { reactive, ref, onMounted,  onBeforeMount, onUnmounted, computed, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer } from '@/utils'
import { useStore } from 'vuex'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const uploadPictureRef=ref(null)
const uploadPictureExplainRef=ref(null)
const store=useStore()
const props = defineProps({
  type: String,   //空内容为无knowledgepointid和id新创建;insert为有knowledgepointId插入;update为有question和id更新;edit为有question但无id和knowledgeid编辑
  knowledgepointId: Number,
  recoverQuestionList:Function     //用于edit恢复题目并刷新题目列表
})
const editor = ref(null) // 富文本编辑器 ref
const questionRef = ref(null)
const route = useRoute()
const router = useRouter()
const knowledgepointOption = reactive([])
const questionTypeOption = [
  {
    value : 1,
    label : '选择题',
  },
  {
    value : 2,
    label : '填空题',
  },
    {
    value : 0,
    label : '简答题',
  },
]
const difficultyLevelOption = [
{
    value : 1,
    label : '入门',
  },
  {
    value : 2,
    label : '中级',
  },
  {
    value : 3,
    label : '较难',
  },
  {
    value : 4,
    label : '高级',
  },
  {
    value : 5,
    label : '压轴',
  },
]
const openLevelOption = [
  {
    value : 'public',
    label : '所有人可见',
  },
  {
    value : 'private',
    label : '仅自己可见',
  },
  {
    value : 'friend',
    label : '好友可见',
  },
]
const validateKnowledgepoint = (rule, value, callback) => {
  if (value<0) {
    callback(new Error('没有选择知识点'))
  }else {
    callback()
  }
}
const state = reactive({
  visible: false,   //控制本组件的弹窗是否可视
  uploadImgServer, // 上传图片的接口地址，单图上传
  token: localGet('token') || '', // 存在本地的 token
  pictures: "",
  questionForm:{          //题目表单
    id:-1,
    content: "可以直接从word复制过来",
    pictures: "",         //跟数据表中对应的字段内容
    answer: "",
    images:[],
    explain: "",
    pictures_explain: "",   //同上 
    images_explain:[],
    reference: "",
    type: 1,
    difficulty_level: 2, 
    open_level: "public",
    knowledgepoint: -1,

  },
  rules: { // 规则
    content: [
      {required: 'true', message: '请填写题目内容', trigger: ['change']}
    ],
    knowledgepoint: [
      {required: 'true', message: '请选择知识点', trigger: ['change']},
      {validator: validateKnowledgepoint, trigger: 'blur'}
    ],
    answer: [
      { required: 'true', message: '请填写参考答案', trigger: ['change'] }
    ],
    explain: [
      { required: 'true', message: '请填写解析', trigger: ['change'] }
    ],
    type: [
      { required: 'true', message: '请选择题型', trigger: ['change'] }
    ],
    difficulty_level: [
      { required: 'true', message: '请选择难度', trigger: ['change'] }
    ],    
  },
})

onMounted(() => {
  if (props.type==""||props.type=="update"){
    getChoiceList()
  }else{
    if(props.type=="insertWithKnowledgeId"){
      state.questionForm.knowledgepoint = props.knowledgepointId
    }
  }
  if(props.type=="edit" || props.type=="update"){
    //从全局状态中获取题目表单，深拷贝
    if(store.state.question){
      Object.assign(state.questionForm, store.state.question)
    }
    getChoiceList()
  }
})
const initQuestion=()=>{
  state.questionForm={          //题目表单
    id:-1,
    content: "可以直接从word复制过来",
    answer: "",
    explain: "",
    pictures: "",         //跟数据表中对应的字段内容
    images:[],    
    pictures_explain: "",   //同上 
    images_explain:[],
    reference: "",
    type: 1,
    difficulty_level: 2, 
    open_level: "private",
    knowledgepoint: -1,
  }
}
// 提交表单（待修改，分4种不同情况）
const submitAddOneQuestion = () => {
  questionRef.value.validate((vaild, obj) => {
    if (vaild) {
      var re = /<br>/g
      var re2 = /<p>/g
      var re3 = /<\/p>/g
      let params = {
        // id: state.questionForm.id,
        answer: state.questionForm.answer.replace(re, "\n").replace(re2, "").replace(re3, "\n"),
        explain: state.questionForm.explain.replace(re, "\n").replace(re2, "").replace(re3, "\n"),
        content: state.questionForm.content.replace(re, "\n").replace(re2, "").replace(re3, "\n"),
        pictures: state.questionForm.pictures,
        reference: state.questionForm.reference,
        type: state.questionForm.type,
        difficulty_level: state.questionForm.difficulty_level,
        knowledgepoint: state.questionForm.knowledgepoint,
        open_level: state.questionForm.open_level,
        top: state.questionForm.top,
        pictures_explain: state.pictures_explain
      }     
      if(props.type=="insertWithKnowledgeId" || props.type=="insert" || props.type=="update"){
        // 默认新增insert用 post 方法
        let httpOption = axios.post
        if(props.type=="update"){
          // 修改题目使用 put 方法
          params.id = state.questionForm.id
          httpOption = axios.put
        }
        httpOption('/questions/', params).then((result) => {
          if(result.code==200){
            ElMessage.success( '操作成功！')
            var r=confirm("点取消继续录入，确定返回首页!");
            if (r==true){
                router.push("/")
            }else{
              initQuestion()
            }
          }else{
            console.log("提交错误", result.message)
          }       
        })
      }else{
        if(props.type=="edit"){     
          store.commit("setQuestion",state.questionForm)
          if(props.recoverQuestionList){
            props.recoverQuestionList()
          }          
        }
      }
      state.visible=false
    }else{                //输出表单没有通过的原因
      console.log("表单没有通过！",obj)
      for (let key in obj) {
        console.log(obj[key][0].message)
        return false;
      }   
    }
  })
}

// 从后台读取知识点列表
const getChoiceList =()=>{
  axios.get(`/knowledgepoints?size=100`).then(res =>{
    if (res.code == 200){
      const temp_list = res.data.results
      knowledgepointOption.splice(0)
      for (let i=0; i<temp_list.length; i++){
        knowledgepointOption.push({value:temp_list[i].id, label:temp_list[i].name})
      }
    }else{
      console.log("error", res)
    }
  }) 
}
//打开弹窗,如果是edit或update，则从全局状态中初始化本组件的question表单
const open = (knowledgepointId) => {
  if(knowledgepointId & knowledgepointId>=0){
    state.questionForm.knowledgepoint = knowledgepointId    
  }
  if(props.type=="edit" || props.type=="update"){
    //从全局状态中获取题目表单，深拷贝
    if(store.state.question){
      Object.assign(state.questionForm, store.state.question)
    }
    getChoiceList()
  }  
  state.visible = true
};
// 关闭弹窗
const close = () => {
  state.visible = false
};
defineExpose({ open, close })
</script>


<style scoped>

</style>